package com.frejoys.task;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.frejoys.common.config.ValueConfig;
import com.frejoys.common.constant.CommonConstant;
import com.frejoys.common.enums.EStatus;
import com.frejoys.common.util.CacheKeyUtil;
import com.frejoys.common.util.huajuan.SDKClient;
import com.frejoys.dao.entity.huajuan.HuajuanScore;
import com.frejoys.dao.entity.huajuan.HuajuanUser;
import com.frejoys.dao.mapper.huajuan.HuajuanUserMapper;
import com.frejoys.service.UserService;
import com.frejoys.service.huajuan.HuajuanScoreService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;

// 花卷云任务
@Slf4j
@Component
@RequiredArgsConstructor
public class HuajuanTask {

    // @Scheduled(cron = "{秒数} {分钟} {小时} {日期} {月份} {星期}")

    private final RedissonClient redissonClient;

    private final ValueConfig valueConfig;

    private final HuajuanUserMapper huajuanUserMapper;

    private final HuajuanScoreService huajuanScoreService;

    private final UserService userService;


    private boolean alreadyRun = false;

    /**
     * 处理花卷云用户信息同步
     *
     */
    // @Async
    // @Scheduled(cron = "0 */2 * * * ?")
    // @Scheduled(cron = "0 0 3-4 * * ?") // 早3点到晚4点每小时执行
    // @Scheduled(cron = "0/60 * * * * ?")
    public void dispatchHuajuanUserQueue() {
        if (alreadyRun) {
            return;
        }
        alreadyRun = true;

        RLock lock = redissonClient.getLock(CacheKeyUtil.taskHuajuanUserLockKey());

        if (lock.tryLock()) {

            SDKClient client = SDKClient.getInstance(valueConfig.getHuajuanyunAppKey(), valueConfig.getHuajuanyunAppSecret(), valueConfig.getHuajuanyunApiUrl());

            try {

                Integer requestId = null;

                while (true) {

                    HashMap<String, Object> params = new HashMap<>();
                    params.put("pagesize", 100);

                    if (requestId != null) {
                        params.put("request_id", requestId);
                    }

                    String response = client.executeApi(CommonConstant.huajuanUserList, params);
                    if (StrUtil.isNotEmpty(response)) {
                        JSONObject json = JSONUtil.parseObj(response);

                        if (json.getInt("code") == 0) {

                            String data = json.getStr("data");
                            if (StrUtil.isNotEmpty(data)) {
                                JSONObject dataObj = JSONUtil.parseObj(data);
                                requestId = dataObj.getInt("request_id");

                                JSONArray dataArray = dataObj.getJSONArray("list");

                                if (dataArray.isEmpty()) {
                                    break;
                                }

                                for (Object ds : dataArray) {
                                    JSONObject dsObj = JSONUtil.parseObj(ds);

                                    String phone = dsObj.getStr("mobile");
                                    Integer huajuanUserId = dsObj.getInt("id");

                                    HuajuanUser hjUser = huajuanUserMapper.getInfo(phone);
                                    if (hjUser == null) {
                                        Long userId = userService.getUserIdByPhone(phone);
                                        if (userId != null) {
                                            huajuanUserMapper.saveInfo(phone, huajuanUserId, userId);
                                        }
                                    }
                                }

                            } else {
                                break;
                            }

                        } else {
                            break;
                        }

                    } else {
                        break;
                    }

                }

            } finally {
                if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                    lock.unlock();
                }
            }
        }

    }

    /**
     * 处理花卷云用户积分同步
     *
     */
    @Async
    // @Scheduled(cron = "0 */2 * * * ?")
    @Scheduled(cron = "0/60 * * * * ?")
    public void dispatchHuajuanScoreQueue() {

        RLock lock = redissonClient.getLock(CacheKeyUtil.taskHuajuanUserScoreLockKey());

        if (lock.tryLock()) {

            try {

                List<HuajuanScore> list = huajuanScoreService.getWaitList(1, 100);

                if (!list.isEmpty()) {

                    SDKClient client = SDKClient.getInstance(valueConfig.getHuajuanyunAppKey(), valueConfig.getHuajuanyunAppSecret(), valueConfig.getHuajuanyunApiUrl());

                    for (HuajuanScore e : list) {

                        String response = null;

                        // 增加
                        if (e.getType().equals(1)) {

                            HashMap<String, Object> params = new HashMap<>();
                            params.put("user_id", e.getHuajuanUserId());
                            params.put("safe_str", e.getMsgSn());
                            params.put("score", e.getScore());
                            params.put("desc", e.getMsgSn());
                            response = client.executeApi(CommonConstant.huajuanScoreAdd, params);

                        } else if (e.getType().equals(2)) {

                            // 消耗
                            HashMap<String, Object> params = new HashMap<>();
                            params.put("user_id", e.getHuajuanUserId());
                            params.put("safe_str", e.getMsgSn());
                            params.put("score", e.getScore());
                            params.put("desc", e.getMsgSn());
                            response = client.executeApi(CommonConstant.huajuanScoreUse, params);

                        }

                        if (response != null) {
                            JSONObject json = JSONUtil.parseObj(response);
                            if (json.getInt("code") == 0) {
                                huajuanScoreService.upScoure(e.getMsgSn(), EStatus.on.getValue());
                            } else if (json.getInt("code") == 100014) {
                                huajuanScoreService.upScoure(e.getMsgSn(), EStatus.on.getValue());
                            }
                        }
                    }

                }

            } finally {
                if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                    lock.unlock();
                }
            }
        }

    }









}
